package com.vf.cloud.rendering.common.util;

import java.util.HashMap;
import java.util.Map;
import com.jfinal.kit.JsonKit;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;

public class DispatchUtil {


	public static void sendPing(ChannelHandlerContext ctx, long time) {
		Map<String, Object> clientConfig = new HashMap<String, Object>();
		clientConfig.put("type", "ping");
		clientConfig.put("time", time);
		send(ctx, JsonKit.toJson(clientConfig));
	}
	
	
	public static void sendSuccess(ChannelHandlerContext ctx, long time) {
		Map<String, Object> success = new HashMap<String, Object>();
		success.put("type", "event");

		Map<String, Object> data = new HashMap<String, Object>();
		data.put("func_name", "OnSuccess");
		data.put("time", time);
		success.put("data", data);
		send(ctx, JsonKit.toJson(success));
	}

	public static void sendFail(ChannelHandlerContext ctx, long time, String message) {
		Map<String, Object> failed = new HashMap<String, Object>();
		failed.put("type", "event");
		Map<String, Object> data = new HashMap<String, Object>();
		data.put("func_name", "OnFailed");
		data.put("time", time);
		data.put("message", message);
		failed.put("data", data);
		send(ctx, JsonKit.toJson(failed));
	}

	public static void send(ChannelHandlerContext ctx, String json) {
		if (ctx != null) {
			ctx.channel().writeAndFlush(new TextWebSocketFrame(json)).addListener(new ChannelFutureListener() {
				@Override
				public void operationComplete(ChannelFuture future) throws Exception {
					if (future.isSuccess()) {
					} else {
					}
				}
			});
		}
	}

	public static void send(ChannelHandlerContext ctx, String json, long time) {
		if (ctx != null) {
			ctx.channel().writeAndFlush(new TextWebSocketFrame(json)).addListener(new ChannelFutureListener() {
				@Override
				public void operationComplete(ChannelFuture future) throws Exception {
					if (future.isSuccess()) {
						sendSuccess(ctx, time);
					} else {
					}
				}
			});
		}
	}


}
